using UnityEngine;
using UnityEngine.EventSystems;

public class UIJS_JoyStick_Script : MonoBehaviour,
    // IBeginDragHandler, 
    IDragHandler, 
    IEndDragHandler
{
    [Header("所操控对象的移动速度")] 
    public float speed = 20f;
    [Header("可拖拽的半径")] 
    public float moveRadius = 60f;
    
    private Vector3 originalPosition;
    private float distance;
    private Vector3 direction;
    // private Transform player;
    private CharacterController player;

    private void Awake()
    {
        // player = GameObject.FindGameObjectWithTag("Player").transform;
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterController>();
    }

    private void Start()
    {
        originalPosition = transform.position;
    }

    private void Update()
    {
        // 实现player角色移动：move是每帧移动所以乘以Time.deltaTime，而simpleMove是每秒移动所以不乘(否则会因为移动值过小而不移动)。
        // player.position += new Vector3(direction.x, 0, direction.y).normalized * speed * Time.deltaTime;
        // player.Move(new Vector3(direction.x, 0, direction.y).normalized * speed * Time.deltaTime);
        player.SimpleMove(new Vector3(direction.x, 0, direction.y).normalized * speed/2);
    }

    // public void OnBeginDrag(PointerEventData eventData)
    // {
    //     
    // }

    public void OnDrag(PointerEventData eventData)
    {
        // 初始原点位置指向鼠标位置的 方向向量
        direction = Input.mousePosition - originalPosition;
        // 计算鼠标与原点的距离
        distance = direction.magnitude;// Vector3.Distance(Input.mousePosition, originalPosition);
        if (distance < moveRadius)
        {
            // 实现拖拽
            transform.position = Input.mousePosition;
        }
        else
        {
            // 遥感位置在范围内跟随鼠标方向
            transform.position = direction.normalized * moveRadius + originalPosition;
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        // 停止拖拽后， 遥感回到原始位置
        transform.position = originalPosition;
        // 停止拖拽后， 方向向量归0
        direction = Vector3.zero;
    }
}